#include "app_message_handler.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "string.h"
#include "app_user.h"

#define TAG "app_message_handler"
#define MESSAGE_QUEUE_SIZE 64

static void message_handler_task(void *pvParameters);

QueueHandle_t message_queue;

typedef struct
{
    char *data;
    int len;
} app_message_t;

void app_message_handler_send(char *data, int len)
{
    app_message_t message = {
        .data = data,
        .len = len,
    };

    xQueueSend(message_queue, &message, 0);
}

void test_handler_task(void *arg)
{
    int cnt = 0;
    char buf[32];
    while (1)
    {
        sprintf(buf, "Test message %d", cnt++);
        app_message_handler_send(buf, strlen(buf));
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

void app_message_handler_init()
{
    // 创建消息队列
    message_queue = xQueueCreate(MESSAGE_QUEUE_SIZE, sizeof(app_message_t));
    xTaskCreate(message_handler_task, "message_handler_task", 2048, NULL, 10, NULL);
    // FIXME: 测试临时 使用
    xTaskCreate(test_handler_task, "test_handler_task", 2048, NULL, 10, NULL);
}


static void message_handler_task(void *pvParameters)
{
    app_message_t message;
    while (1)
    {
        if (xQueueReceive(message_queue, &message, portMAX_DELAY))
        {
            // FIXME: 处理消息 ==》 应该调用对应的处理函数
            ESP_LOGI(TAG, "Received message: %.*s", message.len, message.data);

            char data_id[3] = {message.data[4], message.data[5], '\0'};
            unsigned char id = (unsigned char) strtol(data_id, NULL, 16);

            switch (id)
            {
            case 0x01:  //LED
            
                break;
            
            case 0x02:  //震动
                
                break;
            case 0x03:  //血氧
                
                break;
            case 0x11:  //用户
                app_user_message_handler(message.data, message.len);
                break;
            case 0x12:  //配置wifi信息
                app_wifi_message_handler(message.data, message.len);
                break;
            default:
                printf("Unknown message id: %d\n", id);
                break;
            }





        }
    }
}